class Request {
  private configs: any
  constructor(configs: any) {
    this.configs = {
      baseURL: import.meta.env.VITE_BASE_API_URL,
      header: {
        'content-type': 'application/json;charset=UTF-8',
      },
      ...configs,
    }
  }

  request(options: any = {}) {
    // eslint-disable-next-line no-async-promise-executor
    return new Promise(async (resolve, reject) => {
      const urlRegExp = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?/
      options.url = urlRegExp.test(options.url) ? options.url : (this.configs.baseURL + (options.url.indexOf('/') === 0 ? options.url : `/${options.url}`))
      options.key = options.key || options.url
      options.method = options.method || this.configs.method || 'POST'
      options.header = Object.assign({}, this.configs.header, options.header)
      options.baseURL = this.configs.baseURL
      const result: any = await $fetch(options.url, options)
      if (result.code === 1000)
        resolve(result.data)
      else
        reject(new Error(result.message))
    })
  }

  /**
   * 发送 GET 请求
   * @param url 请求 URL
   * @param body 请求参数
   * @param config 其他配置信息
   */
  get(url: string, data: any = {}, config: any = {}) {
    return this.request({
      url,
      method: 'GET',
      query: data,
      ...config,
    })
  }

  /**
   * 发送 POST 请求
   * @param url 请求 URL
   * @param data 请求数据
   * @param config 其他配置信息
   */
  post(url: string, data: any = {}, config: any = {}) {
    return this.request({
      url,
      method: 'POST',
      body: data,
      ...config,
    })
  }
}

export const useHttp = new Request({})
